#include "snow.h"

TextureManager* tex_snow;

CSnowstorm::CSnowstorm(int numParticles, Vector3f origin, float height, float width, float depth)
  : m_height(height), m_width(width), m_depth(depth), CParticleSystem(numParticles, origin)
{
}

//#define FRAND (rand()/(RAND_MAX+0.5))//
#define FRAND   (((float)rand()-(float)rand())/RAND_MAX)

void CSnowstorm::InitializeParticle(int index)
{
  m_particleList[index].m_pos[1] = m_height;
  m_particleList[index].m_pos[0] = m_origin[0] + FRAND * m_width;
  m_particleList[index].m_pos[2] = m_origin[2] + FRAND * m_depth;

  m_particleList[index].m_size = SNOWFLAKE_SIZE;

  m_particleList[index].m_velocity[0] = SNOWFLAKE_VELOCITY[0] + FRAND * VELOCITY_VARIATION[0];
  m_particleList[index].m_velocity[1] = SNOWFLAKE_VELOCITY[1] + FRAND * VELOCITY_VARIATION[1];
  m_particleList[index].m_velocity[2] = SNOWFLAKE_VELOCITY[2] + FRAND * VELOCITY_VARIATION[2];
}



void CSnowstorm::Update(float elapsedTime)
{
  for (int i = 0; i < m_numParticles; )
  {
      m_particleList[i].m_prevPos = m_particleList[i].m_pos;
    m_particleList[i].m_pos = m_particleList[i].m_pos + m_particleList[i].m_velocity * elapsedTime;

    if (m_particleList[i].m_pos[1] <= m_origin[1])
    {
      m_particleList[i] = m_particleList[--m_numParticles];
    }
    else
    {
      ++i;
    }
  }

  m_accumulatedTime += elapsedTime;

  int newParticles = SNOWFLAKES_PER_SEC * m_accumulatedTime;

  m_accumulatedTime -= 1.0f/(float)SNOWFLAKES_PER_SEC * newParticles;

  Emit(newParticles);
}


void CSnowstorm::Render()
{
  // enable alpha blending and texturing
  //glEnable(GL_BLEND);
  glEnable(GL_TEXTURE_2D);

  // set the blend mode
  //glBlendFunc(GL_SRC_ALPHA, GL_ONE);

  // select the snow texture
  glBindTexture(GL_TEXTURE_2D, m_texture);
  //glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

  // to avoid constant dereferencing...
  Vector3f partPos;
  float size;

  // draw the quads
  glColor3f(1,0,0);
  glBegin(GL_QUADS);
  for (int i = 0; i < m_numParticles; ++i)
  {
    partPos = m_particleList[i].m_pos;
    size = m_particleList[i].m_size;
    glTexCoord2f(0.0, 1.0);
    glVertex3f(partPos[0], partPos[1], partPos[2]);
    glTexCoord2f(1.0, 1.0);
    glVertex3f(partPos[0] + size, partPos[1], partPos[2]);
    glTexCoord2f(1.0, 0.0);
    glVertex3f(partPos[0] + size, partPos[1] - size, partPos[2]);
    glTexCoord2f(0.0, 0.0);
    glVertex3f(partPos[0], partPos[1] - size, partPos[2]);
  }
  glEnd();

  glDisable(GL_BLEND);
  glDisable(GL_TEXTURE_2D);
}

void CSnowstorm::InitializeSystem()
{
  CParticleSystem::InitializeSystem();
}


void CSnowstorm::KillSystem()
{
  CParticleSystem::KillSystem();
}
